<template>
  <antd-menu
    v-model="currentMenu"
    :open-keys="openedMenu"
    :menus="menus"
    :inlineIndent="14"
    theme="dark"
    mode="inline"
    @click="onClick"
    @openChange="onOpenChange"
  />
</template>

<script>
import { computed, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { get } from 'lodash-es';
import { go } from '../router/index.js';
import { useSideMenuStore } from '../pinia/sideMenu.js';

export default {
  name: 'SideMenu',
  setup() {
    const route = useRoute();
    const sideMenuStore = useSideMenuStore();
    const menus = computed(() => sideMenuStore.menus);
    const currentMenu = ref([]);
    const openedMenu = ref([]);

    const getParentMenus = (menus, key, value, field) => {
      const getValue = (item, field) => {
        return field !== undefined ? get(item, field) : item;
      };
      const getParents = (res, parent, field) => {
        return parent ? [getValue(parent, field)].concat(res) : res;
      };
      const deep = (menus, key, value, field, parent) => {
        if (!menus || !menus.length) return [];
        return menus.reduce((res, item) => {
          if (get(item, key) === value) {
            return getParents(res, parent, field);
          }
          const parents = deep(item.children, key, value, field, item);
          if (parents.length) {
            return [].concat(getParents(res, parent, field), parents);
          }
          return res;
        }, []);
      };
      return deep(menus, key, value, field).filter((item) => item !== undefined);
    };

    const onClick = ({ key }) => {
      go(sideMenuStore.getMenuData(key));
    };
    const onOpenChange = (openKeys) => {
      openedMenu.value = openKeys;
    };
    watch(
      route,
      () => {
        const menuKey = sideMenuStore.getMenuData('path', route.fullPath, 'key');
        if (menuKey) {
          currentMenu.value = [menuKey];
          openedMenu.value = getParentMenus(menus.value, 'key', menuKey, 'key');
        }
      },
      {
        immediate: true,
      }
    );
    return { menus, currentMenu, openedMenu, onClick, onOpenChange };
  },
};
</script>

<style scoped lang="less"></style>
